// 添加QR码生成库
function loadQRLibrary() {
  return new Promise((resolve, reject) => {
    if (window.qrcode) {
      resolve();
      return;
    }
    // 由于qrcode.min.js已经在manifest中声明，这里直接resolve
    resolve();
  });
}

// 创建DOM元素
const container = document.createElement('div');
container.className = 'qr-container';

const icon = document.createElement('div');
icon.className = 'qr-icon';

// 获取favicon的函数
async function getFavicon() {
  try {
    const favicon = document.querySelector('link[rel="icon"]')?.href || 
                   document.querySelector('link[rel="shortcut icon"]')?.href || 
                   window.location.origin + '/favicon.ico';
    
    // 测试图片是否可用
    const img = new Image();
    await new Promise((resolve, reject) => {
      img.onload = resolve;
      img.onerror = reject;
      img.src = favicon;
    });
    
    return favicon;
  } catch (error) {
    // 如果获取失败，返回默认的QR码图标SVG
    return ``;
  }
}

// 设置图标
getFavicon().then(iconSrc => {
  icon.innerHTML = `
    <img src="${iconSrc}" alt="QR Code Icon" style="width: 100%; height: 100%; object-fit: contain;">
  `;
});

const modal = document.createElement('div');
modal.className = 'qr-modal';

const qrImage = document.createElement('img');
qrImage.className = 'qr-code';

const downloadBtn = document.createElement('button');
downloadBtn.className = 'download-btn';
downloadBtn.textContent = '下载二维码';

modal.appendChild(qrImage);
modal.appendChild(downloadBtn);
container.appendChild(icon);
container.appendChild(modal);
document.body.appendChild(container);

// 点击图标显示/隐藏二维码
icon.addEventListener('click', async () => {
  if (modal.style.display === 'block') {
    modal.style.display = 'none';
  } else {
    try {
      await loadQRLibrary();
      generateQR();
      modal.style.display = 'block';
    } catch (error) {
      console.error('无法生成二维码:', error);
      alert('生成二维码时出错，请稍后重试');
    }
  }
});

// 生成二维码
async function generateQR() {
  try {
    // 获取网站favicon
    const favicon = document.querySelector('link[rel="icon"]')?.href || 
                   document.querySelector('link[rel="shortcut icon"]')?.href || 
                   window.location.origin + '/favicon.ico';

    // 创建二维码
    const qr = qrcode(0, 'M');
    qr.addData(window.location.href);
    qr.make();

    // 创建临时canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const size = 256;
    canvas.width = size;
    canvas.height = size;

    // 绘制二维码
    const tempImage = new Image();
    await new Promise((resolve, reject) => {
      tempImage.onload = resolve;
      tempImage.onerror = reject;
      tempImage.src = qr.createDataURL(10);
    });
    ctx.drawImage(tempImage, 0, 0, size, size);

    // 在中心绘制favicon
    try {
      const faviconImg = new Image();
      faviconImg.crossOrigin = 'anonymous';  // 处理跨域问题
      
      await new Promise((resolve, reject) => {
        faviconImg.onload = resolve;
        faviconImg.onerror = reject;
        faviconImg.src = favicon;
      });

      // 计算favicon的位置和大小
      const faviconSize = 60;
      const padding = 5;  // 白色背景padding
      const totalSize = faviconSize + (padding * 2);
      const startX = (size - totalSize) / 2;
      const startY = (size - totalSize) / 2;

      // 绘制白色背景
      ctx.fillStyle = 'white';
      ctx.fillRect(startX, startY, totalSize, totalSize);

      // 绘制favicon
      ctx.drawImage(faviconImg, 
        startX + padding, startY + padding, 
        faviconSize, faviconSize
      );
    } catch (error) {
      console.warn('无法加载favicon:', error);
      // favicon加载失败时不显示中心图标
    }

    // 设置最终图片
    qrImage.src = canvas.toDataURL('image/png');
  } catch (error) {
    console.error('生成二维码失败:', error);
    throw error;
  }
}

// 下载二维码
downloadBtn.addEventListener('click', () => {
  try {
    const link = document.createElement('a');
    link.download = `qrcode-${new Date().getTime()}.png`;
    link.href = qrImage.src;
    link.click();
  } catch (error) {
    console.error('下载二维码失败:', error);
    alert('下载二维码失败，请稍后重试');
  }
}); 